package cn.com.wdjedu.androidapp.wjeduandroid.mvp;

import android.annotation.TargetApi;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import cn.com.wdjedu.androidapp.wjeduandroid.db.WJEdudb;
import cn.com.wdjedu.androidapp.wjeduandroid.support.lib.mvputils.BasePresenter;
import cn.com.wdjedu.androidapp.wjeduandroid.ui.BaseFragment;
import nl.nl2312.rxcupboard.RxCupboard;
import nl.nl2312.rxcupboard.RxDatabase;


/**
 * Created by samson on 26/11/2016.
 */

public abstract class MvpFragment<P extends BasePresenter> extends BaseFragment {
    protected P mvpPresenter;
    private SQLiteDatabase db ;
    public RxDatabase rxCupboard ;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        this.mvpPresenter = createPresenter();
        if (db==null)
            db = WJEdudb.getConnection(getActivity());
        if (rxCupboard==null)
            rxCupboard = RxCupboard.withDefault(db);
        super.onCreate(savedInstanceState);
    }

    protected abstract P createPresenter();

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mvpPresenter != null){
            mvpPresenter.dettach();
        }
    }

    /** Fragment当前状态是否可见 */
    protected boolean isVisible;


    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1)
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        if(getUserVisibleHint()) {
            isVisible = true;
            onVisible();
        } else {
            isVisible = false;
            onInvisible();
        }
    }


    /**
     * 可见
     */
    protected void onVisible() {
        lazyLoad();
    }


    /**
     * 不可见
     */
    protected void onInvisible() {


    }

    @Override
    public void onDestroyView() {
//        Datamanage.getInstance().getImageLoader(this.getActivity()).clearMemoryCache();
//        Datamanage.getInstance().getImageLoader(this.getActivity()).clearDiskCache();
        super.onDestroyView();
    }

    /**
     * 延迟加载
     * 子类必须重写此方法
     */
    protected abstract void lazyLoad();
}